package com.example.day27_videocall_server;

import android.media.MediaCodec;
import android.media.MediaFormat;
import android.util.Log;
import android.view.Surface;

import java.nio.ByteBuffer;

/**
 * Description:H265解析器
 * Created by Gdu on 2021/1/5 11:35.
 */

public class DecodecPlayerLiveH265 {
    int width = 1080;
    int height = 1920;
    private MediaCodec mediaCodec;
    public static final String TAG = "DecodecPlayerLiveH265";
    public void initDecoder(Surface removeSurface) {
        try {
            mediaCodec = MediaCodec.createDecoderByType(MediaFormat.MIMETYPE_VIDEO_HEVC);
            MediaFormat format = MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_HEVC, width, height);
            format.setInteger(MediaFormat.KEY_BIT_RATE, width * height);
            format.setInteger(MediaFormat.KEY_FRAME_RATE, 15);
            format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 5);
            mediaCodec.configure(format,removeSurface,null,0);
            mediaCodec.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void callBack(byte[] data) {
        Log.i(TAG, "======" + data.length);
        int inIndex = mediaCodec.dequeueInputBuffer(100000);
        if (inIndex >= 0) {
            ByteBuffer inputBuffer = mediaCodec.getInputBuffer(inIndex);
            inputBuffer.clear();
            inputBuffer.put(data,0,data.length);
            mediaCodec.queueInputBuffer(inIndex,0,data.length,
                    System.currentTimeMillis(),0);
        }
        MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();
        int outIndex = mediaCodec.dequeueOutputBuffer(bufferInfo, 100000);
        while (outIndex>=0){
            mediaCodec.releaseOutputBuffer(outIndex,true);
            outIndex=mediaCodec.dequeueOutputBuffer(bufferInfo,0);
        }
    }
}
